package com.sdy.supermarket.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.controller.BaseController;
import com.sdy.supermarket.biz.model.GsOrder;
import com.sdy.supermarket.biz.model.GsOrderItem;
import com.sdy.supermarket.biz.model.GsResIntention;
import com.sdy.supermarket.biz.service.ApplyService;
import com.sdy.supermarket.biz.service.GsOrderItemService;
import com.sdy.supermarket.biz.service.GsOrderService;
import com.sdy.supermarket.biz.service.GsResIntentionService;
import com.sdy.supermarket.biz.vo.ResOrderDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 资源申请
 * </p>
 *
 * @author zzq
 * @since 2019-07-09
 */
@Slf4j
@RestController
@RequestMapping("/gsOrder")
@SuppressWarnings("unchecked")
public class GsOrderController extends BaseController {
    @Autowired
    private GsOrderService gsOrderService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private GsResIntentionService gsResIntentionService;
    @Autowired
    private GsOrderItemService gsOrderItemService;

    /**
     * 根据订单id查询详情
     *
     * @return Response
     */
    @GetMapping("/get")
    public Response get(String orderNo) {
        return Response.success(gsOrderService.getByOrderNo(orderNo));
    }

    /**
     * 根据订单id查询详情、根据用户id查询所有订单
     *
     * @param userId 用户id
     * @param state  订单状态 0 未提交，1 已提交
     * @return Response
     */
    @GetMapping("/listOrder")
    public Response listOrder(Integer userId, Integer state) {
        LambdaQueryWrapper<GsOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, GsOrder::getUserId, userId)
                .eq(state != null, GsOrder::getState, state)
                .orderByAsc(GsOrder::getId);
        return Response.success(gsOrderService.list(wrapper));
    }

    /**
     * 获取历史版本信息
     *
     * @param orderNo
     * @param versionNo
     * @return
     */
    @GetMapping("/getVersionOrderInfo")
    public Response getVersionOrderInfo(String orderNo, Integer versionNo, HttpServletRequest request) throws BizException {
        GsOrderItem versionOrder = gsOrderItemService.getOne(Wrappers.<GsOrderItem>lambdaQuery().eq(GsOrderItem::getVersionNo, orderNo + "-" + versionNo));
        Assert.isNull(versionOrder, "找不到该历史信息");
        UserInfo userInfo = ssoService.getUserInfo(request);
        ResOrderDetailVO orderDetail = gsOrderService.getOrderDetail(versionOrder.getOrderNo(), versionOrder.getId(), userInfo.getUserId());
        orderDetail.setFlowList(null);
        return Response.success(orderDetail);
    }

    /**
     * 查看购物车项目
     * orderNo 订单号，如果null，则返回未完成订单
     *
     * @return Response
     */
    @GetMapping("/getOrderFullInfo")
    public Response listOrderItem(String orderNo, HttpServletRequest request) throws BizException {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        GsOrder order;
        if (StringUtil.isBlank(orderNo)) {
            order = gsOrderService.getUncompletedOrderFullInfo(userId);
        } else {
            order = gsOrderService.getOrderFullInfo(orderNo);
        }
        return Response.success(order);
    }

    /**
     * 待确认订单
     */
    @GetMapping("/toConfirmOrder")
    public Response toConfirmOrder(HttpServletRequest request, Integer resId) {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        List<GsOrderItem> itemList = gsOrderService.toConfirmOrder(userId, resId);
        return Response.success(itemList);
    }

    /**
     * 删除购物车内容
     *
     * @param itemIdList 待删除id
     * @param checked    是否下架内容
     * @param request
     * @return
     * @throws BizException
     */
    @PostMapping("/removeOrderItem")
    public Response removeItem(@RequestBody List<Integer> itemIdList, Boolean checked, HttpServletRequest request) throws BizException {
        checked = checked == null ? false : checked;
        Assert.isTrue(CollectionUtils.isEmpty(itemIdList) && !checked, "参数错误");
        applyService.removeOrderItem(itemIdList, ssoService.getUserInfo(request).getUserId(), checked);
        return Response.success();
    }

    /**
     * 新增订单
     *
     * @param gsOrderItem 订单对象
     * @return Response
     */
    @PostMapping("/addOrderItem")
    public Response addOrderItem(@RequestBody GsOrderItem gsOrderItem, HttpServletRequest request) throws BizException {
        Assert.isNull(gsOrderItem.getResId(), "参数错误");
        gsOrderItem.setUserId(ssoService.getUserInfo(request).getUserId());
        applyService.newOrder(gsOrderItem);
        return Response.success();
    }

    /**
     * 修改订单
     * <p>
     * //     * @param order
     *
     * @param request
     * @return
     */
    @PostMapping("/updateOrder")
    public Response updateOrderItem(@RequestBody GsOrderItem gsOrderItem, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Integer userId = userInfo.getUserId();
        gsOrderItem.setUserId(userId);
        int updateOrder = applyService.updateOrder(gsOrderItem);
        return updateOrder == 1 ? Response.success("修改成功") : Response.error("修改失败");
    }

    /**
     * 提交订单-确认前一步
     *
     * @param itemIdList 资源id列表
     * @return Response
     */
    @PostMapping("/submit")
    public Response submit(@RequestBody List<Integer> itemIdList, HttpServletRequest request) throws Exception {
        applyService.submitOrder(itemIdList, ssoService.getUserInfo(request).getUserId());
        return Response.success();
    }

    /**
     * 确认订单
     *
     * @param gsOrder 订单对象
     * @return Response
     */
    @PostMapping("/confirm")
    public Response confirm(@RequestBody GsOrder gsOrder, HttpServletRequest request) throws Exception {
        // 非空字段校验
        UserInfo user = ssoService.getUserInfo(request);
        gsOrder.setUserId(user.getUserId());
        gsOrder.setUserName(user.getUserName());
        applyService.newApply(gsOrder);
        return Response.success(gsOrder.getOrderNo());
    }

    /**
     * 添加用户意向
     */
    @PostMapping("/addIntention")
    public Response addIntention(HttpServletRequest request, @RequestBody GsResIntention intention) {
        intention.setUserId(ssoService.getUserInfo(request).getUserId());
        return Response.success(gsResIntentionService.createIntention(intention));
    }
}
